﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using Clandestine.Base;

namespace Clandestine.Graphics
{
	internal static class LoadingContextPool  // static justifiable here, because context resource sharing happens application-wide.
	{
		const int poolSize = 1;  // due to my stupidity, we never background load, so there's no point in having more than one.  
								 // probably going to remove all the LoadingContext stuff if a use case doesn't show up...
		static Dictionary<LoadingContext, bool> lcIsInUse = new Dictionary<LoadingContext, bool>();

		static LoadingContextPool()
		{
			for (int i = 0; i < poolSize; i++)
				lcIsInUse.Add(new LoadingContext(), false);
		}

		internal static LoadingContext GrabContext()
		{
			Stopwatch waiting = new Stopwatch();
			waiting.Start();

			while (true)
			{
				lock (lcIsInUse)
					foreach (LoadingContext lc in lcIsInUse.Keys)
						if (!lcIsInUse[lc])
						{
							lcIsInUse[lc] = true;
							return lc;
						}

				Thread.Sleep(5);
			}
		}

		internal static void ReleaseContext(LoadingContext lc)
		{
			lock (lcIsInUse)
			{
				if (!lcIsInUse[lc])
					Log.w("LoadingContext symmetry broken - trying to release a LoadingContext that has already been released!  Check your code, this stuff is important!");
				else
					lcIsInUse[lc] = false;
			}
		}
	}
}
